<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    title="TrackOut"
    width="90%">
    <dynForm
      ref="dataForm"
      :info-form="infoForm"
      :search-tags="searchTags"
    />
    <div class="opt-btns">
      <h4>{{ $t('exceptionRecord') }}</h4>
      <el-button type="success" size="small" @click="handleAddCol">{{ $t('add') }}</el-button>
    </div>
    <dynTable
      ref="dynTable"
      :loading="false"
      :table-data="tableData"
      :table-columns="tableColumns"
    />
    <div class="materials">
      <span :style="{fontWeight: 'bold'}">{{ $t('materialInformation') }}</span>
      <div class="materials-list">
        <div v-for="(item, index) of materialsData" :key="index" class="materials-item">
          <div class="opt-btns">
            <span>{{ $t('itemNumber') }}: {{ item.materialNo }}({{ item.materialRatio }})</span>
            <el-button size="small" type="success" @click="addMaterialsColumn(item)">{{ $t('add') }}</el-button>
          </div>
          <dynTable
            :loading="false"
            :table-data="item.materialList"
            :table-columns="materialsColumns"
          />
        </div>
      </div>
    </div>
    <div class="material-box">
      <h4>{{ $t('cartridgeInformation') }}</h4>
      <!-- vif保证每次打开弹窗自动聚焦 -->
      <div v-if="dialogVisible" class="material-inputs">
        <div
          v-for="item of materialBoxBarcode"
          :key="item.id"
          class="material-inputs-item"
        >
          <el-input
            v-enterFocus="addMaterialInputs"
            v-model="item.value"
            :style="{width: '320px'}"
            clearable
          />
        </div>
      </div>
    </div>
    <span slot="footer">
      <el-button
        icon="el-icon-circle-close"
        @click="handleClose"
      >{{ $t("cancel") }}</el-button>
      <el-button
        :loading="trackOutLoading"
        type="primary"
        icon="el-icon-receiving"
        @click="doSave"
      >{{ $t("save") }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { doTrackOut, getReasonCode, updateToolingMaterialInfo } from '@/api/production/webOUI'
import { replaceStr } from '@/utils/notification'
import { deepClone } from '@/utils/myTools'
var count = 0
export default {
  name: 'ModelTrackOut',
  data() {
    const searchTags = [
      { label: this.$t('eqpName'), prop: 'eqpId', tag: 'DynInput', disabled: true },
      { label: this.$t('LotNumebr'), prop: 'lotId', tag: 'DynInput', disabled: true },
      { label: this.$t('completedJobsNums'), prop: 'lotQty', tag: 'DynInput', disabled: true },
      { label: this.$t('numberOfGoods'), prop: 'output', tag: 'DynInput', disabled: true }
    ]
    const tableColumns = [
      { prop: 'codeType', label: this.$t('exceptionType'), templete: (_scope) => {
        return (
          <el-select vModel={_scope.row.codeType} vOn:change={() => this.getReasonTypeCode(_scope.row.codeType, _scope)}>
            {this.codeTypeList.map(item => {
              return (
                <el-option
                  key={item.id}
                  label={item.name}
                  value={item.id}>
                </el-option>
              )
            })}
          </el-select>
        )
      } },
      { prop: 'reasonCode', label: this.$t('exceptionreason'), templete: (_scope) => {
        return (
          <el-select vModel={_scope.row.reasonCode} filterable vOn:change={() => this.setReasonDesc(_scope.row)}>
            {_scope.row.reasonCodeList.map((item, index) => {
              return (
                <el-option
                  key={index}
                  label={item.reasonDesc}
                  value={item.reasonCode}>
                </el-option>
              )
            })}
          </el-select>
        )
      } },
      { prop: 'reasonQty', label: this.$t('numberAbnormalities'), templete: (_scope) => {
        return (
          <el-input-number v-model={_scope.row.reasonQty}
            controls-position='right' min={0}
            vOn:change={() => this.getOutPutNums(_scope.row)}
          ></el-input-number>
        )
      } },
      { prop: 'reasonSN', label: this.$t('exceptionSerialNumber'), templete: (_scope) => {
        return (
          <el-input
            vModel={_scope.row.reasonSN}
            clearable>
          </el-input>
        )
      } },
      { prop: '', label: this.$t('action'), width: '100px', templete: (_scope, _this) => {
        return (
          <el-link
            type='primary'
            underline={false}
            on-click={() => this.handlerDelete(_scope)}
          >
            {this.$t('delete')}
          </el-link>
        )
      } }
    ]
    const materialsColumns = [
      { prop: 'materialLotNo', label: this.$t('naterialBatchNumber'), templete: (_scope) => {
        return (
          <el-input
            vModel={_scope.row.materialLotNo}
            nativeOnKeyup={(code) => this.splitMaterialLotNo(code, _scope.row.materialLotNo, _scope.row)}
            clearable>
          </el-input>
        )
      } },
      { prop: 'bomNums', label: this.$t('BOM_quantity'), width: '150px', templete: (_scope) => {
        return (
          <el-input
            value={_scope.row.bomNums}
            clearable>
          </el-input>
        )
      } },
      { prop: 'materialQty', label: this.$t('actual_amount'), width: '150px', templete: (_scope) => {
        return (
          <el-input-number v-model={_scope.row.materialQty}
            controls-position='right'
            min={0}
            style={{ width: '120px' }}
          ></el-input-number>
        )
      } },
      { prop: '', label: this.$t('action'), width: '80px', templete: (_scope, _this) => {
        return (
          <el-link
            type='primary'
            underline={false}
            on-click={() => this.scopedDelete(_scope, _this)}
          >
            {this.$t('delete')}
          </el-link>
        )
      } }
    ]
    return {
      dialogVisible: false,
      trackOutLoading: false,
      infoForm: {},
      selectList: {},
      searchTags: Object.freeze(searchTags),
      tableData: [],
      materialBoxBarcode: [{ id: count, value: '' }],
      tableColumns: Object.freeze(tableColumns),
      materialsData: [],
      codeTypeList: [{ name: this.$t('abnormal'), id: 'loss' }, { name: this.$t('Rework'), id: 'irework' }],
      reasonList: [], // 保存所有数据, change时直接根据type获取对应字段
      materialsColumns: Object.freeze(materialsColumns)

    }
  },
  methods: {
    async handleOpen(form) {
      const { materialList, ...obj } = form
      this.infoForm = obj
      this.$set(this.infoForm, 'output', obj.lotQty)
      const materialsData = (materialList || [])
        .map(v => ({ materialNo: v.materialNo, materialRatio: v.materialRatio, materialList: [] }))
      this.materialsData = materialsData
      this.getReasonCodeList()
      this.dialogVisible = true
    },
    addMaterialInputs() {
      this.materialBoxBarcode.push({
        id: ++count,
        value: ''
      })
    },
    doSave() {
      this.trackOutLoading = true
      updateToolingMaterialInfo({ eqpId: this.infoForm.eqpId }).then(res => {
        this.$betterTips(res, this.handlerTrackOut)
      })
    },
    handlerTrackOut() {
      doTrackOut({
        eqpId: this.infoForm.eqpId,
        lotId: this.infoForm.lotId,
        outputList: [{
          output: this.infoForm.output,
          type: 'Normal',
          reasonList: this.tableData.map(c => {
            delete c.reasonCodeList
            return c
          }),
          materialInfo: deepClone(this.materialsData).map(c => {
            c.materialList = c.materialList.filter(n => n.materialLotNo && n.materialQty !== '').map(v => {
              delete v.bomNums
              return v
            })
            return c
          })
        }],
        materialBoxBarcode: this.materialBoxBarcode.filter(v => v.value).map(c => c.value)
      }).then(res => {
        if (res.code === 1) {
          this.trackOutLoading = false
          this.$alert(replaceStr(this.$t(String(res.message)), res.data), this.$t('trackOutInfo'), {
            confirmButtonText: this.$t('determine'),
            type: 'success',
            callback: action => {
              const strForm = JSON.stringify(this.infoForm)
              const form = JSON.parse(strForm)
              this.$emit('trackOutGetLotInfo', form.lotId)
              this.handleClose()
              // this.handleUpdate()
            } })
        } else {
          this.$alert(replaceStr(this.$t(String(res.message)), res.data), this.$t('trackOutInfo'), {
            confirmButtonText: this.$t('determine'),
            type: 'error',
            callback: () => {
              this.trackOutLoading = false
            }
          })
        }
      }, () => {
        this.trackOutLoading = false
      })
    },
    handleClose() {
      Object.assign(this.$data, this.$options.data.call(this))
    },
    handleUpdate() {
      const strForm = JSON.stringify(this.infoForm)
      const form = JSON.parse(strForm)
      this.$emit('trackOutGetLotInfo', form.lotId)
    },
    handleAddCol() {
      this.tableData.push({ reasonCodeList: [] })
    },
    addMaterialsColumn(data) {
      data.materialList.push({ bomNums: Number(data.materialRatio) * Number(this.infoForm.lotQty), materialQty: Number(data.materialRatio) * Number(this.infoForm.lotQty) })
    },
    setReasonDesc(row) {
      if (row.codeType === 'loss') {
        const item = this.reasonList.lossCode.find(c => c.reasonCode === row.reasonCode)
        row.reasonDesc = item.reasonDesc
      } else if (row.codeType === 'irework') {
        const item = this.reasonList.reworkCode.find(c => c.reasonCode === row.reasonCode)
        row.reasonDesc = item.reasonDesc
      }
    },
    getOutPutNums() {
      const minus = this.tableData.filter(v => v.codeType === 'loss' | !v.codeType && v.reasonQty).reduce((t, c) => {
        return Number(t) + Number(c.reasonQty)
      }, 0)
      const plus = this.tableData.filter(v => v.codeType === 'irework' && v.reasonQty).reduce((t, c) => {
        return Number(t) + Number(c.reasonQty)
      }, 0)
      const output = Number(this.infoForm.lotQty) + Number(plus) - Number(minus)
      this.$set(this.infoForm, 'output', output)
    },
    getReasonTypeCode(value, row) {
      row.row.reasonCode = ''
      row.row.reasonQty = 0
      this.getOutPutNums()
      if (value === 'loss') {
        this.$set(this.tableData, row.$index, { ...row.row, reasonCodeList: this.reasonList.lossCode })
      } else if (value === 'irework') {
        this.$set(this.tableData, row.$index, { ...row.row, reasonCodeList: this.reasonList.reworkCode })
      }
    },
    splitMaterialLotNo(keycode, value, row) {
      if (keycode.code === 'Enter') {
        row.materialLotNo = value.split(';')[1]
      }
    },
    getReasonCodeList() {
      getReasonCode({ stepId: this.infoForm.stepId }).then(res => {
        this.reasonList = res.data
      })
    },
    scopedDelete(row, data) {
      data.tableData.splice(row.$index, 1)
    },
    handlerDelete(row) {
      this.tableData.splice(row.$index, 1)
    }
  }
}
</script>
<style lang="scss" scoped>
.opt-btns{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    margin-bottom: 10px;
}
.material-box{
    width: 100%;
    margin-bottom: 20px;
    .material-inputs{
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        .material-inputs-item{
            width: 340px;
            margin: 0 0 10px 20px;
        }
    }
}
.materials {
  .materials-list{
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    .materials-item{
      width: calc(50% - 20px);
      padding: 10px;
      span{
        display: inline-block;
        padding: 10px 0;
      }
    }
  }
}
</style>
